package com.bsoft.gol.editor.service.impl;

import com.bsoft.gol.editor.service.EditorQuestionnaireApi;
import ctd.access.controller.AccessTokenController;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.util.context.ContextUtils;
import com.bsoft.gol.editor.dao.*;
import com.bsoft.gol.editor.editor.*;
import com.bsoft.gol.editor.editor.qo.AuthorityRemoveQo;
import com.bsoft.gol.editor.editor.qo.EditorAuthorityQo;
import com.bsoft.gol.editor.editor.qo.EditorQuestionnaireQo;
import com.bsoft.gol.editor.editor.qo.UpdatetypeQo;
import com.bsoft.gol.editor.editor.response.EditorQuestionnaireDetailRes;
import com.bsoft.gol.editor.editor.response.EditorQuestionnaireTitleRes;
import com.bsoft.gol.editor.editor.response.QueryEditorQuestionnaireListResponse;
import hcn.base.Dept;
import hcn.bean.QueryAuthorityOrgListQo;
import hcn.bean.vo.QueryAuthorityOrgListVo;
import hcn.util.BaseRespUtil;
import hcn.util.BaseResponse;
import hcn.bean.UserAllVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pcn.service.web.BaseDeviceService;
import service.rpc.DeptInfoServiceIntf;
import service.rpc.OrganizationInfoIntf;
import com.bsoft.gol.editor.utils.CommonUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 问卷表
 *
 * @author sumu
 */
@Service("editorQuestionnaireApi")
public class EditorQuestionnaireApiImpl implements EditorQuestionnaireApi {
    private final static Logger log = LoggerFactory.getLogger(EditorQuestionnaireApiImpl.class);

    /**
     * 运行状态
     */
    public static final int STATE_RUNING = 2;

    private static Logger logger = LoggerFactory.getLogger(EditorQuestionnaireApiImpl.class);

    @Autowired
    private EditorQuestionnaireDAO editorQuestionnaireDAO;
    @Autowired
    private EditorQuestionnaireStyleDAO editorQuestionnaireStyleDAO;
    @Autowired
    private EditorQuestionnaireTitleDAO editorQuestionnaireTitleDAO;
    @Autowired
    private EditorTitleOptionDAO editorTitleOptionDAO;
    @Autowired
    private EditorSkipLogicDAO editorSkipLogicDAO;
    @Autowired
    private EditorDisplayLogicDAO editorDisplayLogicDAO;
    @Autowired
    private EditorUserDAO editorUserDAO;
    @Autowired
    private EditorAuthorityDAO editorAuthorityDAO;
    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;
    @Autowired
    private DeptInfoServiceIntf deptInfoServiceIntf;
    @Autowired
    private EditorQuestionnaireOfficialDAO editorQuestionnaireOfficialDAO;
    @Autowired
    private OrganizationInfoIntf organizationInfoIntf;

    @Override
//    @RpcService
    public String addQuestionnaire(EditorQuestionnaire req) throws ControllerException {
        EditorQuestionnaire insert = new EditorQuestionnaire();
        if (CommonUtils.isEmpty(req.getQuestionnaireId())) {
            if (StringUtils.isNotEmpty(req.getQuestionnaireName())) {
                insert.setQuestionnaireName(req.getQuestionnaireName());
                insert.setQuestionnaireVersion(BigDecimal.valueOf(0.1));
                insert.setQuestionnaireState((byte) 1);
                String uuid = UUID.randomUUID().toString();
                insert.setQuestionnaireId(uuid);
                insert.setIfReuse(req.getIfReuse());
                insert.setIfToday(req.getIfToday());
                if (CommonUtils.isNotEmpty(req.getHasSubtitle())) {
                    insert.setHasSubtitle(req.getHasSubtitle());
                } else {
                    insert.setHasSubtitle(1);
                }
                insert.setQuestionnaireFlag((byte) 1);
                insert.setQuestionnaireDate(new Date());
                insert.setQuestionnaireCode(UUID.randomUUID().toString());
                insert.setCreateTime(new Date());

                UserAllVo userAllVo = null;
                userAllVo = baseDeviceService.getAllByOnline();
                if (Objects.nonNull(userAllVo)) {
                    String userId = userAllVo.getUserId();
                    insert.setCreateId(userId);
                    String orgId = userAllVo.getLocalOrgId();
                    String orgName = userAllVo.getOrgName();
                    String deptId = userAllVo.getLocalDeptId();
                    String deptName = userAllVo.getDeptName();

                    insert.setOrgId(orgId);
                    insert.setDeptId(deptId);

                } else if (CommonUtils.isNotEmpty(req.getLoginUserId())) {
                    insert.setCreateId(req.getLoginUserId());
                    EditorUser editorUser = editorUserDAO.get(req.getLoginUserId());

                    insert.setOrgId(editorUser.getOrgId());
                    insert.setOrgName(editorUser.getOrgName());
                    insert.setDeptId(editorUser.getDepartmentId());
                    insert.setDeptName(editorUser.getDepartmentName());
                }
                if (CommonUtils.isNotEmpty(req.getOrgId())) {
                    insert.setOrgId(req.getOrgId());
                }
                if (CommonUtils.isNotEmpty(req.getQuestionnaireType())) {
                    insert.setQuestionnaireType(req.getQuestionnaireType());
                } else {
                    insert.setQuestionnaireType((byte) 1);
                }
                editorQuestionnaireDAO.save(insert);
                if (CommonUtils.isEmpty(req.getType())) {
                    insert.setType("1");
                    QueryAuthorityOrgListQo qo = new QueryAuthorityOrgListQo();
                    ArrayList<String> modeCode = new ArrayList<>();
                    modeCode.add("0154");
                    qo.setModuleCodeList(modeCode);
                    List<QueryAuthorityOrgListVo> queryAuthorityOrgListVos = organizationInfoIntf.queryAuthorityOrgList(qo);
                    log.info("quert--------------------"+queryAuthorityOrgListVos.size());
                    UserRoleToken current = UserRoleToken.getCurrent();
                    if (CommonUtils.isNotEmpty(queryAuthorityOrgListVos)) {
                        for (QueryAuthorityOrgListVo queryAuthorityOrgListVo : queryAuthorityOrgListVos) {
                            EditorAuthority editorAuthority = new EditorAuthority();
                            editorAuthority.setQuestionnaireId(insert.getQuestionnaireId());
                            editorAuthority.setCreateId(current.getUserId());
                            editorAuthority.setId(UUID.randomUUID().toString());
                            editorAuthority.setAuthorityDept("");
                            editorAuthority.setAuthorityDeptName("");
                            editorAuthority.setAuthorityOrg(queryAuthorityOrgListVo.getOrgId());
                            editorAuthority.setAuthorityOrgName(queryAuthorityOrgListVo.getOrganizationName());
                            editorAuthority.setType("1");
                            editorAuthority.setCreateTime(new Date());
                            editorAuthority.setStatus("1");
                            editorAuthority.setAlterId(current.getUserId());
                            editorAuthority.setAlterTime(new Date());
                            editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                            editorAuthorityDAO.save(editorAuthority);
                        }
                    } else {
                        throw new ControllerException("未查询到拥有该模块下面的机构列表,无法添加表单");
                    }
                } else {
                    insert.setType(req.getType());
                }
                return uuid;
            }
        } else {
            EditorQuestionnaire questionnaire = editorQuestionnaireDAO.get(req.getQuestionnaireId());
            if (CommonUtils.isEmpty(req.getType())) {
                req.setType(questionnaire.getType());
            }
            ctd.util.BeanUtils.copy(req, questionnaire);
            questionnaire.setQuestionnaireDate(new Date());
            questionnaire.setQuestionnaireWithTitle(req.getQuestionnaireWithTitle());
            questionnaire.setUpdateId(req.getLoginUserId());
            editorQuestionnaireDAO.update(questionnaire);
            return req.getQuestionnaireId();
        }
        return null;
    }

    /**
     * 表单列表分页
     *
     * @return pageInfo
     */
    @Override
    public BaseResponse<QueryEditorQuestionnaireListResponse> pageList(EditorQuestionnaireQo req) throws ControllerException {
        BaseResponse<QueryEditorQuestionnaireListResponse> baseResponse = new BaseResponse<>();
        editorQuestionnaireDAO.updateEditorQuestionnaireFlags();
        QueryEditorQuestionnaireListResponse editorQuestionnaireListResponse = new QueryEditorQuestionnaireListResponse();
        //问卷id集合
        QueryAuthorityOrgListQo qo = new QueryAuthorityOrgListQo();
        ArrayList<String> modeCode = new ArrayList<>();
        modeCode.add("0154");
        qo.setModuleCodeList(modeCode);
        List<QueryAuthorityOrgListVo> queryAuthorityOrgListVos = organizationInfoIntf.queryAuthorityOrgList(qo);
        ArrayList<String> orgList = new ArrayList<>();
        if (CommonUtils.isNotEmpty(queryAuthorityOrgListVos)) {
            for (QueryAuthorityOrgListVo queryAuthorityOrgListVo : queryAuthorityOrgListVos) {
                orgList.add(queryAuthorityOrgListVo.getOrgId());
                req.setOrgList(orgList);
            }
        }
        List<String> questionnaireIdList = editorQuestionnaireDAO.queryEditorByorgId(req);
        EditorQuestionnaireQo editorQuestionnaireQo = new EditorQuestionnaireQo();
        UserRoleToken current = UserRoleToken.getCurrent();
        if (CommonUtils.isNotEmpty(current)){
            editorQuestionnaireQo.setLoginUserId(current.getUserId());
            List<String> reqq = editorQuestionnaireDAO.queryEditorByorgId(editorQuestionnaireQo);
            if (CommonUtils.isNotEmpty(reqq)){
                if (CommonUtils.isNotEmpty(questionnaireIdList)){
                    questionnaireIdList.addAll(reqq);
                }else {
                    questionnaireIdList = new ArrayList<>();
                    questionnaireIdList.addAll(reqq);
                }
            }
        }
        if (CommonUtils.isEmpty(questionnaireIdList)){
            editorQuestionnaireListResponse.setTotal(0L);
            editorQuestionnaireListResponse.setList(new ArrayList<>());
            baseResponse.setData(editorQuestionnaireListResponse);
            return baseResponse;
        }
        removeDuplicate(questionnaireIdList);
        req.setQuestionnaireIdList(questionnaireIdList);
        List<EditorQuestionnaire> editorQuestionnaires = editorQuestionnaireDAO.queryEditorQuestionnaireList(req);
        editorQuestionnaireListResponse.setList(editorQuestionnaires);
        editorQuestionnaireListResponse.setTotal(editorQuestionnaireDAO.queryEditorQuestionnaireCount(req));
        baseResponse.setData(editorQuestionnaireListResponse);
        return baseResponse;
    }

    //通过HashSet踢除重复元素
    public static List removeDuplicate(List list) {
        if (hcn.util.CommonUtils.isNotEmpty(list)) {
            HashSet h = new HashSet(list);
            list.clear();
            list.addAll(h);
        }
        return list;
    }

    /**
     * 修改表单类型
     *
     * @param req
     * @return pageInfo
     */
    @Override
    public BaseResponse updatetype(UpdatetypeQo req) {
        BaseResponse baseResponse = new BaseResponse();
        if ("3".equals(req.getType())) {
            editorAuthorityDAO.updateStatus(req.getQuestionnaireId());
            //需要吧当前用户加进这个权限列表里面
            UserRoleToken current = UserRoleToken.getCurrent();
            if (CommonUtils.isNotEmpty(current)) {
                EditorAuthority editorAuthorityByUserId = editorAuthorityDAO.getEditorAuthorityByUserId(req.getQuestionnaireId(), current.getUserId());
                if (CommonUtils.isNotEmpty(editorAuthorityByUserId)) {
                    editorAuthorityByUserId.setQuestionnaireId(req.getQuestionnaireId());
                    editorAuthorityByUserId.setAuthorityUser(current.getUserId());
                    editorAuthorityByUserId.setAuthorityUserName(current.getUserName());
                    editorAuthorityByUserId.setCreateId(current.getUserId());
                    editorAuthorityByUserId.setAlterId(current.getUserId());
                    editorAuthorityByUserId.setAlterTime(new Date());
                    editorAuthorityByUserId.setStatus("1");
                    editorAuthorityByUserId.setType("3");
                    editorAuthorityDAO.update(editorAuthorityByUserId);
                } else {
                    EditorAuthority editorAuthority = new EditorAuthority();
                    editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                    editorAuthority.setQuestionnaireId(req.getQuestionnaireId());
                    editorAuthority.setAuthorityUser(current.getUserId());
                    editorAuthority.setAuthorityUserName(current.getUserName());
                    editorAuthority.setCreateId(current.getUserId());
                    editorAuthority.setCreateTime(new Date());
                    editorAuthority.setAlterId(current.getUserId());
                    editorAuthority.setAlterTime(new Date());
                    editorAuthority.setStatus("1");
                    editorAuthority.setType("3");
                    editorAuthorityDAO.save(editorAuthority);
                }
            }
        }
        editorQuestionnaireDAO.updateEditorQuestionnaireType(req.getQuestionnaireId(), req.getType());
        return baseResponse;
    }

    /**
     * 删除问卷表单
     *
     * @param questionnaireId id
     */
    @Override
    public void removeQuestionnaire(String questionnaireId) {
        if (StringUtils.isNotEmpty(questionnaireId)) {
            editorQuestionnaireDAO.updateEditorQuestionnaireFlag(questionnaireId);
        }
    }

    /**
     * 更新表单状态
     *
     * @param questionnaireId    id
     * @param questionnaireState state
     */
    @Override
    public void editState(String questionnaireId, Byte questionnaireState) {
        editorQuestionnaireDAO.updateEditorQuestionnaireState(questionnaireId, questionnaireState);
    }

    /**
     * 复制表单
     *
     * @return 复制后的id
     */
    @Override
    public String copyQuestion(EditorQuestionnaire req) {
        EditorQuestionnaire questionnaire = editorQuestionnaireDAO.get(req.getQuestionnaireId());
        EditorQuestionnaire editorQuestionnaire = new EditorQuestionnaire();
        editorQuestionnaire.setQuestionnaireMould(questionnaire.getQuestionnaireMould());
        editorQuestionnaire.setQuestionnaireName(req.getQuestionnaireName());
        editorQuestionnaire.setQuestionnaireVersion(BigDecimal.valueOf(0.1));
        editorQuestionnaire.setQuestionnaireState((byte) 1);
        String uuid = UUID.randomUUID().toString();
        editorQuestionnaire.setQuestionnaireId(uuid);
        editorQuestionnaire.setQuestionnaireFlag((byte) 1);
        editorQuestionnaire.setQuestionnaireDate(new Date());
        editorQuestionnaire.setQuestionnaireCode(UUID.randomUUID().toString());
        editorQuestionnaire.setCreateTime(new Date());
        editorQuestionnaire.setQuestionnaireType((byte) 1);
        editorQuestionnaire.setCreateId(req.getLoginUserId());
        if (CommonUtils.isNotEmpty(req.getUpdateId())) {
            editorQuestionnaire.setUpdateId(req.getUpdateId());
        }
        editorQuestionnaireDAO.save(editorQuestionnaire);
        String newQuestionnaireId = editorQuestionnaire.getQuestionnaireId();

        copy(req.getQuestionnaireId(), newQuestionnaireId, questionnaire.getType());

        return newQuestionnaireId;
    }

    private void copy(String questionnaireId, String newQuestionnaireId, String type) {
        // 复制外观

        List<EditorQuestionnaireStyle> styles = editorQuestionnaireStyleDAO.queryEditorTitleOptionByQId(questionnaireId);

        if (CommonUtils.isNotEmpty(styles)) {
            // 一个表单一个外观，这里for循环只有一次
            for (EditorQuestionnaireStyle style : styles) {
                style.setQuestionnaireId(newQuestionnaireId);
                style.setQuestionnaireStyleId(UUID.randomUUID().toString());
                style.setCreateTime(new Date());
//                editorQuestionnaireStyleManager.save(style);
            }
        }
        // 复制查询表单下的题目列表
        List<EditorQuestionnaireTitle> titles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByQid(questionnaireId);
        List<String> titleIds = new ArrayList<>();
        // 复制权限
        List<EditorAuthority> editorAuthorityList = editorAuthorityDAO.queryEditorAuthorityByQid(questionnaireId);
        if (CommonUtils.isNotEmpty(editorAuthorityList)) {
            for (EditorAuthority editorAuthority : editorAuthorityList) {
                if ("3" != editorAuthority.getType()) {
                    editorAuthority.setCreateTime(new Date());
                    editorAuthority.setId(UUID.randomUUID().toString());
                    editorAuthority.setQuestionnaireId(newQuestionnaireId);
                    editorAuthorityDAO.save(editorAuthority);
                }
            }
        }
        //并且要把个人添加进表
        UserRoleToken current = UserRoleToken.getCurrent();
        EditorAuthority editorAuthority = new EditorAuthority();
        editorAuthority.setQuestionnaireId(questionnaireId);
        editorAuthority.setCreateId(current.getUserId());
        editorAuthority.setId(UUID.randomUUID().toString());
        editorAuthority.setAuthorityDept("");
        editorAuthority.setAuthorityDeptName("");
        editorAuthority.setAuthorityOrg("");
        editorAuthority.setAuthorityOrgName("");
        editorAuthority.setAuthorityUser(current.getUserId());
        editorAuthority.setAuthorityUserName(current.getUserName());
        editorAuthority.setType("3");
        editorAuthority.setCreateTime(new Date());
        if ("3".equals(type)) {
            editorAuthority.setStatus("1");
        } else {
            editorAuthority.setStatus("0");
        }
        editorAuthority.setAlterId(current.getUserId());
        editorAuthority.setAlterTime(new Date());
        editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
        editorAuthorityDAO.save(editorAuthority);

        if (CommonUtils.isNotEmpty(titles)) {
            Map<String, String> idTemp = new HashMap<>(titles.size());

            for (EditorQuestionnaireTitle title : titles) {
                title.setQuestionnaireId(newQuestionnaireId);
                title.setCreateTime(new Date());
                titleIds.add(title.getTitleId());
                String uuid = UUID.randomUUID().toString();
                idTemp.put(title.getTitleId(), uuid);

                title.setTitleId(uuid);
                editorQuestionnaireTitleDAO.save(title);
            }
            List<EditorTitleOption> columnsets = editorTitleOptionDAO.queryEditorTitleOptionByTitleIds(titleIds);
            Map<String, String> optionIdTemp = new HashMap<>(columnsets.size());
            // 复制选项
            if (CommonUtils.isNotEmpty(columnsets)) {
                for (EditorTitleOption columnset : columnsets) {
                    columnset.setTitleId(idTemp.get(columnset.getTitleId()));
                    String uuid = UUID.randomUUID().toString();
                    optionIdTemp.put(columnset.getOptionId(), uuid);
                    columnset.setOptionId(uuid);
                    editorTitleOptionDAO.save(columnset);
                }
            }
            // 复制跳题逻辑
            List<EditorSkipLogic> skipLogics = editorSkipLogicDAO.queryEditorSkipLogicByTitleIds(titleIds);
            if (CommonUtils.isNotEmpty(skipLogics)) {

                for (EditorSkipLogic logic : skipLogics) {
                    logic.setTitleId(idTemp.get(logic.getTitleId()));
                    logic.setTitleAimId(idTemp.get(logic.getTitleAimId()));
                    logic.setSkipId(UUID.randomUUID().toString());
                    logic.setCreateTime(new Date());
                    logic.setOptionId(optionIdTemp.get(logic.getOptionId()));
                    editorSkipLogicDAO.save(logic);
                }
            }
            // 复制显示逻辑
            List<EditorDisplayLogic> displayLogics = editorDisplayLogicDAO.queryEditorDisplayLogicListByTitleIds(titleIds);
            if (CommonUtils.isNotEmpty(displayLogics)) {
                for (EditorDisplayLogic displayLogic : displayLogics) {
                    displayLogic.setOptionId(optionIdTemp.get(displayLogic.getOptionId()));
                    displayLogic.setTitleId(idTemp.get(displayLogic.getTitleId()));
                    displayLogic.setDisplayId(UUID.randomUUID().toString());
                    displayLogic.setTitleDisplayId(idTemp.get(displayLogic.getTitleDisplayId()));
                    displayLogic.setCreateTime(new Date());
                    editorDisplayLogicDAO.save(displayLogic);
                }
            }
        }
    }

    /**
     * 包含更新版本的逻辑
     *
     * @param questionnaireId id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EditorQuestionnaireDetailRes detail(String questionnaireId) {
        EditorQuestionnaire questionnaire = editorQuestionnaireDAO.get(questionnaireId);
        BigDecimal totalGrade = new BigDecimal(0.00);
        if (CommonUtils.isEmpty(questionnaire)) {
            return new EditorQuestionnaireDetailRes();
        }
        // 发布状态
//        if (questionnaire.getQuestionnaireState() == 3 && questionnaire.getQuestionnaireFlag() == 1) {
        if (questionnaire.getQuestionnaireState() == 2) {

//            questionnaire.setQuestionnaireFlag((byte) 2);
//            editorQuestionnaireDAO.update(questionnaire);
//
//            // 发布状态 复制  更新版本
//            String newQuestionnaireId = UUID.randomUUID().toString();
//            questionnaire.setQuestionnaireId(newQuestionnaireId);
//            BigDecimal questionnaireCode=editorQuestionnaireDAO.queryEditorQuestionnaireCodeList(questionnaire.getQuestionnaireCode()).get(0).getQuestionnaireVersion();
//            questionnaire.setQuestionnaireVersion(questionnaireCode.add(BigDecimal.valueOf(0.1)));
//            questionnaire.setQuestionnaireDate(new Date());
//            questionnaire.setQuestionnaireState((byte) 1);
//            questionnaire.setCreateTime(new Date());
//            questionnaire.setQuestionnaireFlag((byte) 1);
//            editorQuestionnaireDAO.save(questionnaire);
//            copy(questionnaireId, newQuestionnaireId);
//            questionnaireId = newQuestionnaireId;
        }

        EditorQuestionnaireDetailRes detailRes = new EditorQuestionnaireDetailRes();

        BeanUtils.copyProperties(questionnaire, detailRes);
        if (CommonUtils.isNotEmpty(questionnaire) && !"1".equals(questionnaire.getProcessMode())) {
            List<EditorQuestionnaireOfficial> officials = editorQuestionnaireOfficialDAO.queryEditorQuestionnaireOfficialList(questionnaireId);
            detailRes.setOfficials(officials);
        }
        List<EditorQuestionnaireTitle> titles = editorQuestionnaireTitleDAO.queryEditorQuestionnaireTitleByQid(questionnaireId);

        List<String> titleIds = new ArrayList<>();


        if (CommonUtils.isNotEmpty(titles)) {
            List<EditorQuestionnaireTitleRes> titlesRes = new ArrayList<>();
            List<String> titleList = new ArrayList<>();
            Integer pageSize = 0;
            Integer pageNo = 1;

            for (EditorQuestionnaireTitle title : titles) {
                EditorQuestionnaireTitleRes editorQuestionnaireTitleRes = new EditorQuestionnaireTitleRes();
                BeanUtils.copyProperties(title, editorQuestionnaireTitleRes);
                if (CommonUtils.isNotEmpty(editorQuestionnaireTitleRes.getWidgetType()) && editorQuestionnaireTitleRes.getWidgetType() == 10) {
                    pageSize++;
                    editorQuestionnaireTitleRes.setTitleList(titleList);
                    editorQuestionnaireTitleRes.setPageNo(pageNo);
                    pageNo++;
                    titleList = new ArrayList<>();
                } else {
                    titleList.add(editorQuestionnaireTitleRes.getTitleId());
                }
                titlesRes.add(editorQuestionnaireTitleRes);
                titleIds.add(title.getTitleId());

            }
            detailRes.setPageSize(pageSize);
            detailRes.setTitles(titlesRes);

            List<EditorTitleOption> options = editorTitleOptionDAO.queryEditorTitleOptionByTitleIds(titleIds);

            if (CommonUtils.isNotEmpty(options)) {

                Map<String, List<EditorTitleOption>> map = new HashMap<>(options.size());
                for (EditorTitleOption option : options) {

                    EditorTitleOption optionRes = new EditorTitleOption();
                    BeanUtils.copyProperties(option, optionRes);

                    if (map.containsKey(option.getTitleId())) {
                        List<EditorTitleOption> resList = map.get(option.getTitleId());
                        resList.add(optionRes);

                    } else {
                        List<EditorTitleOption> resList = new ArrayList<>();

                        resList.add(optionRes);
                        map.put(optionRes.getTitleId(), resList);
                    }
                }

                for (EditorQuestionnaireTitleRes titleRes : titlesRes) {
                    List<EditorTitleOption> resList = map.get(titleRes.getTitleId());
                    if (CommonUtils.isNotEmpty(resList)) {
                        try {
                            resList.sort(new Comparator<EditorTitleOption>() {
                                @Override
                                public int compare(EditorTitleOption o1, EditorTitleOption o2) {
                                    if (CommonUtils.isNotEmpty(o1) && CommonUtils.isNotEmpty(o2)) {
                                        return o1.getOptionNum().compareTo(o2.getOptionNum());
                                    } else {
                                        return 0;
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        titleRes.setOptions(resList);
                    }
                    //分数统计 1单选题、2多选题、3下拉选、4字典选、5级联选择、6单项填空、7多项填空、8文件上传、9表格矩阵、10分页、11分割线、12备注说明
                    if (titleRes.getWidgetType() != null) {
                        if (titleRes.getWidgetType() == 1 || titleRes.getWidgetType() == 3 || titleRes.getWidgetType() == 14 || titleRes.getWidgetType() == 26 || titleRes.getWidgetType() == 29 || titleRes.getWidgetType() == 30) {
                            BigDecimal max = new BigDecimal(0.00);
                            if (CommonUtils.isNotEmpty(resList)){
                                for (EditorTitleOption editorTitleOption : resList) {
                                    if (CommonUtils.isNotEmpty(editorTitleOption.getOptionGrade())) {
                                        int result = max.compareTo(editorTitleOption.getOptionGrade());
                                        if (result < 0) {
                                            max = editorTitleOption.getOptionGrade();
                                        }
                                    }
                                }
                            }
                            totalGrade = totalGrade.add(max);
                        } else if (titleRes.getWidgetType() == 2 || titleRes.getWidgetType() == 7) {
                            if (CommonUtils.isNotEmpty(resList)){
                                for (EditorTitleOption editorTitleOption : resList) {
                                    if (CommonUtils.isNotEmpty(editorTitleOption.getOptionGrade())) {
                                        totalGrade = totalGrade.add(editorTitleOption.getOptionGrade());
                                    }
                                }
                            }
                        } else if (titleRes.getWidgetType() == 6 && "99".equals(titleRes.getWriteTips())) {
                            if (CommonUtils.isNotEmpty(titleRes.getStartMark())) {
                                double startMark = Double.valueOf(titleRes.getStartMark());
                                String answerContent = titleRes.getStartTotal();
                                Pattern pattern = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
                                Matcher isNum = pattern.matcher(answerContent);
                                if (CommonUtils.isNotEmpty(answerContent) && isNum.matches()) {
                                    double answer = Double.valueOf(answerContent);
                                    double i = startMark * answer;
                                    totalGrade = totalGrade.add(new BigDecimal(i));
                                } else {
                                    totalGrade = totalGrade.add(new BigDecimal(0));
                                }
                            }
                        }
                    }
                }

            }
        }
        detailRes.setTotalGrade(totalGrade);
        return detailRes;

    }

    @Override
    public List<Map<String, Object>> questionVersion(String questionnaireId) {

        EditorQuestionnaire one = editorQuestionnaireDAO.get(questionnaireId);

        List<Map<String, Object>> list = new ArrayList<>();

        if (one != null) {

            List<EditorQuestionnaire> editorQuestionnaires = editorQuestionnaireDAO.queryEditorQuestionnaireListByCode(one.getQuestionnaireCode());

//            if (CommonUtils.isNotEmpty(editorQuestionnaires)) {
//
//                Collections.reverse(editorQuestionnaires);
//                for (EditorQuestionnaire editorQuestionnaire : editorQuestionnaires) {
//                    Map<String, Object> map = new HashMap<>(2);
//                    map.put("questionnaireId", editorQuestionnaire.getQuestionnaireId());
//                    map.put("questionnaireVersion", editorQuestionnaire.getQuestionnaireVersion());
//                    list.add(map);
//                }
//            }

        }

        return list;
    }


    @Override
    public HashMap<String, ArrayList<EditorAuthority>> authorityList(EditorAuthority req) {

        List<EditorAuthority> editorAuthorities = editorAuthorityDAO.queryEditorAuthorityByQid(req.getQuestionnaireId());
        HashMap<String, ArrayList<EditorAuthority>> hashMap = new HashMap<>();
        ArrayList<EditorAuthority> authorityOrg = new ArrayList<>();
        ArrayList<EditorAuthority> authorityDept = new ArrayList<>();
        ArrayList<EditorAuthority> authorityUser = new ArrayList<>();
        if (CommonUtils.isNotEmpty(editorAuthorities)) {
            for (EditorAuthority editorAuthority : editorAuthorities) {
                if ("1".equals(editorAuthority.getType())) {
                    authorityOrg.add(editorAuthority);
                } else if ("2".equals(editorAuthority.getType())) {
                    authorityDept.add(editorAuthority);
                } else if ("3".equals(editorAuthority.getType())) {
                    authorityUser.add(editorAuthority);
                }
            }
        }
        hashMap.put("authorityOrg", authorityOrg);
        hashMap.put("authorityDept", authorityDept);
        hashMap.put("authorityUser", authorityUser);
        return hashMap;
    }


    @Override
    public BaseResponse authorityAdd(EditorAuthorityQo req) {
        BaseResponse<List<EditorAuthority>> response = new BaseResponse<>();
        //缺少权限校验
        if ("1".equals(req.getType())) {
            editorAuthorityDAO.removeByQid(req.getQuestionnaireId(), "1");
            editorAuthorityDAO.updateStatus(req.getQuestionnaireId());
            if (CommonUtils.isNotEmpty(req.getList())) {
                for (EditorAuthorityQo.AuthorityEntity authorityEntity : req.getList()) {
                    EditorAuthority editorAuthority = new EditorAuthority();
                    editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                    editorAuthority.setQuestionnaireId(req.getQuestionnaireId());
                    editorAuthority.setAuthorityOrg(authorityEntity.getId());
                    editorAuthority.setAuthorityOrgName(authorityEntity.getName());
                    editorAuthority.setCreateId(req.getCreateId());
                    editorAuthority.setCreateTime(new Date());
                    editorAuthority.setAlterId(req.getAlterId());
                    editorAuthority.setAlterTime(new Date());
                    editorAuthority.setType("1");
                    editorAuthority.setStatus("1");
                    editorAuthorityDAO.save(editorAuthority);
                }
            }
        } else if ("2".equals(req.getType())) {
            editorAuthorityDAO.removeByQid(req.getQuestionnaireId(), "2");
            editorAuthorityDAO.updateStatus(req.getQuestionnaireId());
            if (CommonUtils.isNotEmpty(req.getList())) {
                for (EditorAuthorityQo.AuthorityEntity authorityEntity : req.getList()) {
                    if (!"1".equals(authorityEntity.getDeptAuthorityFlag())) {
                        EditorAuthority editorAuthority = new EditorAuthority();
                        editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                        editorAuthority.setQuestionnaireId(req.getQuestionnaireId());
                        editorAuthority.setAuthorityOrg(authorityEntity.getParentId());
                        editorAuthority.setAuthorityOrgName(authorityEntity.getParentName());
                        editorAuthority.setAuthorityDept(authorityEntity.getId());
                        editorAuthority.setAuthorityDeptName(authorityEntity.getName());
                        editorAuthority.setCreateId(req.getCreateId());
                        editorAuthority.setCreateTime(new Date());
                        editorAuthority.setAlterId(req.getAlterId());
                        editorAuthority.setAlterTime(new Date());
                        editorAuthority.setType("2");
                        editorAuthority.setStatus("1");
                        editorAuthorityDAO.save(editorAuthority);
                    } else {
                        try {
                            List<Dept> depts = deptInfoServiceIntf.queryConsultUseDeptList(authorityEntity.getParentId());
                            if (CommonUtils.isNotEmpty(depts)) {
                                for (Dept dept : depts) {
                                    EditorAuthority editorAuthority = new EditorAuthority();
                                    editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                                    editorAuthority.setQuestionnaireId(req.getQuestionnaireId());
                                    editorAuthority.setAuthorityOrg(authorityEntity.getParentId());
                                    editorAuthority.setAuthorityOrgName(authorityEntity.getParentName());
                                    editorAuthority.setAuthorityDept(dept.getDeptId());
                                    editorAuthority.setAuthorityDeptName(dept.getName());
                                    editorAuthority.setCreateId(req.getCreateId());
                                    editorAuthority.setCreateTime(new Date());
                                    editorAuthority.setAlterId(req.getAlterId());
                                    editorAuthority.setAlterTime(new Date());
                                    editorAuthority.setType("2");
                                    editorAuthority.setStatus("1");
                                    editorAuthorityDAO.save(editorAuthority);
                                }
                            }
                        } catch (ControllerException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else if ("3".equals(req.getType())) {
            editorAuthorityDAO.removeByQid(req.getQuestionnaireId(), "3");
            editorAuthorityDAO.updateStatus(req.getQuestionnaireId());
            if (CommonUtils.isNotEmpty(req.getList())) {
                for (EditorAuthorityQo.AuthorityEntity authorityEntity : req.getList()) {
                    EditorAuthority editorAuthority = new EditorAuthority();
                    editorAuthority.setId(UUID.randomUUID().toString().replace("-", ""));
                    editorAuthority.setQuestionnaireId(req.getQuestionnaireId());
                    editorAuthority.setAuthorityUser(authorityEntity.getId());
                    editorAuthority.setAuthorityUserName(authorityEntity.getName());
                    editorAuthority.setCreateId(req.getCreateId());
                    editorAuthority.setCreateTime(new Date());
                    editorAuthority.setAlterId(req.getAlterId());
                    editorAuthority.setAlterTime(new Date());
                    editorAuthority.setType("3");
                    editorAuthority.setStatus("1");
                    editorAuthorityDAO.save(editorAuthority);
                }
            }
        }
        List<EditorAuthority> editorAuthorities = editorAuthorityDAO.queryEditorAuthorityByQid(req.getQuestionnaireId());
        response.setData(editorAuthorities);
        return response;
    }

    /* *
     * @description :机构权限删除
     * @author      :zangsf
     * @date        :2022-12-06 10:52
     * @param       :[req]
     * @return      :com.bsoft.gol.editor.editor.BaseResponse
     */
    @Override
    public void authorityRemove(AuthorityRemoveQo req) {
        editorAuthorityDAO.remove(req.getId());
    }
}
